package com.xiaozheng.utils;

import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @Package: com.xiaozheng.utils
 * @ClassName: TransactionManger
 * @Author: 小政同学    QQ:xiaozheng666888@qq.com
 * @CreateTime: 2020/9/27 13:28
 * @What_is_this_file_for: 和事务管理相关的工具类
 * @Description: 包含了开启事务，提交事务，回滚事务和释放连接
 */
@Component
@Aspect //表示该类是个切面类
public class TransactionManger {
    @Autowired
    private ConnectionUtils connectionUtils;

    /*public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }*/
    @Pointcut("execution(* *..service.impl.AccountServiceImpl.*(..))")
    public void cutOffPoint(){}

    /**
     * 开启事务
     */
    @Before("cutOffPoint()")
    public void begin() {
        try {
            connectionUtils.getThreadConnection().setAutoCommit(false);
            System.out.println("开启事务");
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    @AfterReturning("cutOffPoint()")
    public void commit() {
        try {
            connectionUtils.getThreadConnection().commit();
            System.out.println("提交事务");
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    @AfterThrowing("cutOffPoint()")
    public void rollback() {
        try {
            System.out.println("回滚事务");
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    @After("cutOffPoint()")
    public void release() {
        try {
            //换回连接池
            connectionUtils.getThreadConnection().close();
            // 调用removConnection解绑
            connectionUtils.removeConnection();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

}
